<?php
/**
 * Created by PhpStorm.
 * User: 刘抱
 * Date: 2018/9/10
 * Time: 11:19
 */

namespace Home\Controller;


class CrmProjectController extends CommunalController
{
    public function _initialize()
    {
        new LogController();
    }

    //新项目列表页
    public function index()
    {
        parent::check_permission('CRMX-M', '', '');
        $userList = get_userName('');
        $crm_project = M("db_crm_project");
        $db_crm_contact = M("db_crm_contact");
        $where = array();
        $leader = I('leader');
        $stage = I('stage');
        $nature = I('nature');
        $size = I('size');
        $type = I('type');
        $importance = I('importance');
        $company_nature = I('company_nature');
        $project_id = I('project_id');
        $where['del'] = 1;
        $crm_project_array = $crm_project->where($where)->field('project_id,name')->select();
        if (!empty($project_id)) $where['project_id'] = $project_id;
        if (!empty($leader)) $where['leader'] = $leader;
        if (!empty($stage)) $where['stage'] = $stage;
        if (!empty($nature)) $where['nature'] = $nature;
        if (!empty($size)) $where['size'] = $size;
        if (!empty($importance)) $where['importance'] = $importance;
        if (!empty($type)) {
            $where['_string'] = 'FIND_IN_SET('."'$type'".',type)';
        }
        if (!empty($company_nature)) $where['company_nature'] = $company_nature;
        if (get_permission('CRMX-M', 3, '')) {//个人查看
            $where['_string'] = 'add_uid=' . $this->login_id;
        }
        $result = $crm_project->where($where)->order('add_date desc,project_id desc')->select();
        $main_linkman_ids = implode(',', array_unique(array_filter(array_column($result, 'main_linkman'))));
        $other_linkman_ids = implode(',', array_unique(array_filter(array_column($result, 'other_linkman'))));//去空去重
        $res_contact_main = $db_crm_contact->field('contact_id,username,mobilephone')->where("contact_id in ($main_linkman_ids)")->select();
        $res_contact_other = $db_crm_contact->field('contact_id,username,mobilephone')->where("contact_id in ($other_linkman_ids)")->select();
        $new_other = array();
        foreach ($result as $k => $v) {
            foreach ($res_contact_main as $key_main => $value_main) {
                if ($v['main_linkman'] == $value_main['contact_id']) {
                    $result[$k]['main_linkman_info'] = $value_main;
                }
            }
            foreach ($res_contact_other as $m => $n) {
                if (in_array($n['contact_id'], explode(',', $v['other_linkman']))) {//取出重复key
                    $type2 = $v['other_linkman'];
                    !isset($new_other[$type2]) && $new_other[$type2] = array();
                    $new_other[$type2][] = $n;
                }
            }
        }
        $leader_array = array();
        foreach ($result as $k => $v) {
            $result[$k]['type'] = explode(',',$v['type']);
            foreach ($new_other as $m => $n) {
                if ($v['other_linkman'] == $m) {
                    $result[$k]['other_linkman_info'] = array_unique($n, SORT_REGULAR);//二维数组去重
                }
            }
            $leader_array[] = $v['leader'];
        }
        $count = count($result);
        $Page = new \Think\Page($count, 15);
        $result = array_slice($result, $Page->firstRow, $Page->listRows);
        $show = $Page->show();
        $this->assign('result', $result);
        $this->assign('page', $show);
        $this->assign('user_list', $userList);
        $this->assign('project_id', $project_id);
        $this->assign('crm_project_array', $crm_project_array);
        $this->assign('leader', $leader);
        $this->assign('stage', $stage);
        $this->assign('nature', $nature);
        $this->assign('size', $size);
        $this->assign('importance', $importance);
        $this->assign('type', $type);
        $this->assign('company_nature', $company_nature);
        $this->assign('leader_array', array_filter(array_unique($leader_array)));//负责人去重去空
        $this->display();
    }

    //新项目添加页
    public function add()
    {
        $information_id = I('information_id');
        $userList = get_userName('');
        $db_crm_customers_information = M("db_crm_customers_information");//市场信息表
        $db_crm_project = M("db_crm_project");
        $db_crm_project_flow = M("db_crm_project_flow");//项目状态记录表
        $res_information = $db_crm_customers_information->field('information_id,customer_name')->select();//市场信息表信息
        $map['project_num'] = array('like', array('LF%'));
        $project_num = $db_crm_project->field('project_num')->where($map)->order('project_num desc')->limit(1)->find();
        $project_num = !empty($project_num['project_num']) ? substr($project_num['project_num'], 2) : '0000';
        $num = intval($project_num);
        //echo sprintf("%04d", $num+1);
        $project_num = 'LF' . str_pad($num + 1, 4, "0", STR_PAD_LEFT);//自增编号
        if (!empty($_POST)) {
            $X = $_POST['nature'];
            $Y = implode('/0',$_POST['type']);
            $data = $_POST;
            $data['project_num'] = $project_num . '-0' . $X . '-0' . $Y;
            $data['add_uid'] = $flow_data['change_uid'] = $flow_data['add_uid'] = $_SESSION['dms_uid'];
            $data['add_date'] = $flow_data['add_date'] = $flow_data['change_date'] = date('Y-m-d H:i:s');
            $data['other_linkman'] = implode(',', $data['other_linkman']);
            $data['type'] = implode(',', $data['type']);
            //注释无用代码 liubao
            //$info = $db_crm_customers_information->field('information_id,project_id')->where("information_id={$_POST['information_id']}")->find();//市场信息表信息
            try {
                $project_id = $db_crm_project->add($data);
                $flow_data['project_id'] = $project_id;
                $flow_data['stage'] = $_POST['stage'];
                $flow_data['add_user'] = $_SESSION['dms_username'];
                $flow_data['remark'] = '录入项目时初始状态';
                $db_crm_project_flow->add($flow_data);
                //注释无用代码 liubao
                /*if ($info['project_id'] == NULL) {
                    $update['information_id'] = $info['information_id'];
                    $update['project_id'] = $project_id;
                    $db_crm_customers_information->save($update);
                }
                //若市场信息未绑定项目则更新information表中的project_id以绑定就不处理了*/
                $Qywx = new \Qywx\Controller\IndexController();
                $title = $data['name'];
                $description['stage'] = '状态变更为：' . get_project_stage($_POST['stage']);
                $description['leader'] = '负责人：' . get_userName($_POST['leader']);
                $Qywx->push_card_message('stage' . $_POST['stage'], $title, $description, $_SERVER['HTTP_HOST'] . __APP__ . "/Mobile/Crm/project_situation/id/$project_id");
                $this->success("操作成功", __APP__ . "/CrmProject/index");
                die;
            } catch (\Exception $e) {
                $this->error("操作失败", __APP__ . "/CrmProject/index");
                die;
            }
        }
        //添加主要联系人
        $db_crm_contact = M("db_crm_contact");
        $res_crm_contact = $db_crm_contact->select();
        $this->assign('user_list', $userList);
        $this->assign('province_list', $this->get_province_city());
        $this->assign('job_level', $this->get_constant(C("JOB_LEVEL")));
        $this->assign('relation', $this->get_constant(C("DECISION_RELATION")));
        $this->assign('res_crm_contact', $res_crm_contact);
        $this->assign('res_information', $res_information);
        $this->assign('now', date('Y-m-d'));
        $this->assign('information_id', $information_id);
        $this->display();
    }

    //项目状态变更记录
    public function project_flow()
    {
        $data = $_POST;
        $project_id = $_POST['project_id'];
        $data['add_uid'] = $_SESSION['dms_uid'];
        $data['add_user'] = $_SESSION['dms_username'];
        $data['add_date'] = date('Y-m-d H:i:s');
        $db_crm_project_flow = M("db_crm_project_flow");
        $db_crm_project = M("db_crm_project");
        $where['project_id'] = $project_id;
        $where['del'] = 1;
        try {
            $project_flow = $db_crm_project_flow->where($where)->order('add_date desc')->find();
            if (!empty($project_flow) && $project_flow['stage'] == $_POST['stage']) {
                $res['status'] = false;
                $res['msg'] = '您还未变更当前状态';
                echo json_encode($res);
                die;
            } else {
                $db_crm_project_flow->add($data);
                $stage['stage'] = $_POST['stage'];
                $db_crm_project->where($where)->save($stage);
                $Qywx = new \Qywx\Controller\IndexController();
                $project_detail = $this->getCrmProject($project_id);
                $title = $project_detail['name'];
                $description['stage'] = '状态变更为：' . get_project_stage($_POST['stage']);
                $description['leader'] = '负责人：' . get_userName($project_detail['leader']);
                $Qywx->push_card_message('stage' . $_POST['stage'], $title, $description, $_SERVER['HTTP_HOST'] . __APP__ . "/Mobile/Crm/project_situation/id/$project_id");
                $res['status'] = self::YES;
                echo json_encode($res);
                die;
            }
        } catch (\Exception $e) {
            $res['status'] = false;
            $res['msg'] = '更新失败';
            echo json_encode($res);
            die;
        }
    }

    //项目编辑页面
    public function edit()
    {
        $userList = get_userName('');
        $db_crm_customers_information = M("db_crm_customers_information");
        $db_crm_project = M("db_crm_project");
        $project_id = isset($_GET['project_id']) ? $_GET['project_id'] : $_POST['project_id'];
        $res_project = $db_crm_project->where("project_id=$project_id and del=1")->find();
        if (!empty($res_project)) {
            $information_id = $res_project['information_id'];
            $information = $db_crm_customers_information->where("information_id=$information_id")->find();
            if (!empty($_POST)) {
                $project_id = $_POST['project_id'];
                $data = $_POST;
                $data['other_linkman'] = implode(',', $data['other_linkman']);
                $data['type'] = implode(',', $data['type']);
                try {
                    $db_crm_project->where("project_id=$project_id")->save($data);
                    $this->success('更新成功', __APP__ . 'CrmProject/index');
                    die;
                } catch (\Exception $e) {
                    $this->error('更新失败', __APP__ . 'CrmProject/index');
                    die;
                }
            }
            $this->assign('information', $information);
            $this->assign('project_id', $project_id);
            $this->assign('result', $res_project);
            $this->assign('user_list', $userList);
            //添加主要联系人
            $db_crm_contact = M("db_crm_contact");
            $res_crm_contact = $db_crm_contact->select();
            $this->assign('res_crm_contact', $res_crm_contact);
            //添加其他联系人
            $other_linkman_ids = explode(',', $res_project['other_linkman']);
            $types = explode(',', $res_project['type']);
            $this->assign('other_linkman_ids', $other_linkman_ids);
            $this->assign('types', $types);
            $this->assign('province_list', $this->get_province_city(''));
            $this->assign('city_list', $this->get_province_city($res_project['province_id']));
            $this->assign('job_level', $this->get_constant(C("JOB_LEVEL")));
            $this->assign('relation', $this->get_constant(C("DECISION_RELATION")));
            $this->display();
        } else {
            $this->error('无此项目', __APP__ . 'CrmProject/index');
        }
    }

    public function del($project_id)
    {
        $data['del'] = 0;
        try {
            M("db_crm_project")->where("project_id=$project_id")->save($data);
            M("db_crm_project_flow")->where("project_id=$project_id")->save($data);
            $this->success('删除成功', __APP__ . 'CrmProject/index');
        } catch (\Exception $e) {
            $this->error('删除失败', __APP__ . 'CrmProject/index');
        }
    }

    //项目详情页
    public function detail()
    {
        $project_id = I("project_id");
        $res_project = M("db_crm_project")->where("project_id=$project_id")->find();
        $information_id = $res_project['information_id'];
        $information = M("db_crm_customers_information")->where("information_id=$information_id")->find();
        $province = $this->get_province_city($res_project['province_id'], 2);
        $city = $this->get_province_city($res_project['city_id'], 2);
        $res_project['address'] = $province . $city . $res_project['address'];
        $res_project['type'] = explode(',',$res_project['type']);
        $this->assign('result', $res_project);
        $this->assign('information', $information);
        $this->display();
    }

    //获取项目信息
    static public function getCrmProject($project_id)
    {
        $res = M("db_crm_project")->where("project_id=$project_id and del=1")->find();
        return isset($res) ? $res : false;
    }

    //获取项目array信息
    static public function getCrmProjectArray($project_ids)
    {
        $where['project_id'] = array('in', $project_ids);
        $where['del'] = 1;
        $res = M("db_crm_project")->where($where)->select();
        return isset($res) ? $res : false;
    }

    public function getCrmProjectAjax()
    {
        $project_id = I('project_id');
        $result = self::getCrmProject($project_id);
        echo json_encode($result);
        die;
    }

}
